// Copyright (c) 2010 Manuel Peinado Gallego <manuel.peinado@gmail.com>
// Distributed under the MIT license


#include "stdafx.h"
#include "WorldBuilder.h"
#include "Quad.h"


void drawQuad(const Quad & q)
{
	gx::Vec3 n = q.computeNormal();
	glBegin(GL_QUADS);
		glNormal3dv(n.to_array());
		glVertex3dv(q.v0.to_array());
		glVertex3dv(q.v1.to_array());
		glVertex3dv(q.v2.to_array());
		glVertex3dv(q.v3.to_array());
	glEnd();

	glPushAttrib(GL_LIGHTING_BIT | GL_CURRENT_BIT);
		glDisable(GL_LIGHTING);
		glColor3d(1., 1., 0.);
		glBegin(GL_LINES);
			glVertex3dv(q.getCenter().to_array());
			glVertex3dv((q.getCenter() + n*.1).to_array());
		glEnd();
	glPopAttrib();
}


void drawWireQuad(const Quad & q)
{
	glPushAttrib(GL_LIGHTING_BIT | GL_LINE_BIT | GL_CURRENT_BIT);
		glLineWidth(1.5f);
		glDisable(GL_LIGHTING);
		glBegin(GL_LINE_LOOP);
			glVertex3dv(q.v0.to_array());
			glVertex3dv(q.v1.to_array());
			glVertex3dv(q.v2.to_array());
			glVertex3dv(q.v3.to_array());
		glEnd();
	glPopAttrib();
}


Quad::Quad()
: v0(gx::zero), v1(gx::zero), v2(gx::zero), v3(gx::zero)
{
}

Quad::Quad(const gx::Vec3 & v0, const gx::Vec3 & v1, const gx::Vec3 & v2, const gx::Vec3 & v3) 
: v0(v0), v1(v1), v2(v2), v3(v3)
{
	// TODO make sure they're coplanar
}


void Quad::move(const gx::Vec3 & offset)
{
	v0 += offset;
	v1 += offset;
	v2 += offset;
	v3 += offset;
}

gx::Vec3 Quad::computeNormal(void) const
{
	return (v1 - v0).cross(v3 - v0).normalize();
}

gx::Vec3 Quad::getCenter(void) const
{
	return .5 * (v0 + v2);
}




